import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_detail_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/widgets/company_detail_add_admin_bar_widget.dart';
import 'package:e_reception_flutter/ui/company/manager/select_person_page.dart';
import 'package:e_reception_flutter/ui/create_user/create_user/widgets/create_user_edit_widget.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../../app_main.dart';
import '../../common_person_list_response.dart';
import 'class_or_department_page.dart';
import 'class_or_department_viewmodel.dart';
import 'event/admin_change_event.dart';

///班级或部门详情
class ClassOrDepartmentAdminDetail extends StatefulWidget {
  static const String ROUTER = 'ClassOrDepartmentAdminDetail';
  final DepartmentOrClassListItemBean oldBean;
  final int type;
  final List<CommonPersonBean> adminList;

  const ClassOrDepartmentAdminDetail(
      {Key key, this.oldBean, this.type, this.adminList})
      : super(key: key);

  ///跳转方法
  static Future<bool> navigatorPush(
      BuildContext context, DepartmentOrClassListItemBean oldBean, int type,
      {List<CommonPersonBean> adminList}) {
    return RouterUtils.routeForFutureResult<bool>(
      context,
      ClassOrDepartmentAdminDetail(
        oldBean: oldBean,
        type: type,
        adminList: adminList,
      ),
      routeName: ClassOrDepartmentAdminDetail.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return ClassOrDepartmentAdminDetailState();
  }
}

class ClassOrDepartmentAdminDetailState
    extends BaseState<ClassOrDepartmentAdminDetail> {
  bool isError = false;

  ClassOrDepartmentViewModel _viewModel;

  ///管理员列表
  List<CommonPersonBean> adminList = List();

  @override
  void initState() {
    _viewModel = ClassOrDepartmentViewModel(this);
    if (widget.adminList != null) {
      adminList.addAll(widget.adminList);
    }

    super.initState();
    _viewModel.detailValueStream.listen((AdminMemberListBean result) {
      loading(false);
      if (result == null) {
        isError = true;
      } else {
        if (result.adminList != null) {
          adminList.clear();
          adminList.addAll(result.adminList);
        }
      }

      setState(() {
        widget.oldBean.adminCnt = adminList.length;
      });
    });
    _viewModel.getDetail(widget.oldBean.getId());
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(
          children: <Widget>[
            VgTopBarWidget(
                title: widget?.oldBean?.getName() ?? '',
                isShowBack: true,
                rightPadding: 40),
            Expanded(
              child: VgPlaceHolderStatusWidget(
                errorStatus: isError,
                child: Column(
                  children: <Widget>[
                    _adminNumAddBar(),
                    Expanded(
                      child: _adminList(),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///管理员列表
  Widget _adminList() {
    return ListView.builder(
      padding: EdgeInsets.zero,
      itemBuilder: (context, index) {
        return _listItem(adminList[index]);
      },
      itemCount: adminList.length,
      shrinkWrap: true,
    );
  }

  Widget _listItem(CommonPersonBean data) {
    return Container(
      child: _toMainRowWidget(data),
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
    );
  }

  Widget _toMainRowWidget(CommonPersonBean data) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () async {
        if(!AppOverallDistinguish.comefromAiOrWeStudy()){return;}
        //点击弹出移除管理员
        bool result = await CommonConfirmCancelDialog.navigatorPushDialog(
            context,
            title: "提示",
            content: "确定取消${data.name}在该${widget.type== ClassOrDepartmentPage.TYPE_DEPARTMENT?'部门':'班级'}下的管理员资格？",
            cancelText: "取消",
            confirmText: "确定",
            confirmBgColor: Color(0xff1890ff));
        if (result ?? false) {
          _viewModel.deleteAdmin(widget.oldBean,data.userid,BaseCallback(onSuccess: (val){
            loading(false);
            setState(() {
              adminList.remove(data);
              widget.oldBean.adminCnt = adminList.length;
              widget.adminList.remove(data);
            });
          },onError: (e){
            loading(false);
            toast(e);
          }),);

        }
      },
      child: Row(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: GestureDetector(
              onTap: () {
                PersonDetailPage.navigatorPush(context, data.fuid, fid:data.fid);
              },
              behavior: HitTestBehavior.opaque,
              child: Container(
                width: 36,
                height: 36,
                child: VgCacheNetWorkImage(
                  showOriginEmptyStr(data.putpicurl) ??
                      showOriginEmptyStr(data.napicurl ?? "") ??
                      '',
                  fit: BoxFit.cover,
                  imageQualityType: ImageQualityType.middleDown,
                  defaultErrorType: ImageErrorType.head,
                  defaultPlaceType: ImagePlaceType.head,
                ),
              ),
            ),
          ),
          SizedBox(
            width: 10,
          ),
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: (VgStringUtils.checkAllEmpty([
                data.department?.trim(),
                data.projectname?.trim(),
                data.city?.trim(),
                data.classname?.trim(),
                // itemBean?.coursename?.trim(),
              ]))
                  ? MainAxisAlignment.center
                  : MainAxisAlignment.spaceBetween,
              children: <Widget>[
                //姓名
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    CommonNameAndNickWidget(
                      name: data.name,
                      nick: data.nick,
                    ),
                    VgLabelUtils.getRoleLabel(data.roleid) ?? Container(),
                    _toPhoneWidget(data.phone),
                  ],
                ),

                //部门/项目/城市
                _infoWidget(data)
              ],
            ),
          ),
          Spacer(),
          Opacity(
            opacity: AppOverallDistinguish.comefromAiOrWeStudy() || widget?.type==0 ?1 :0,
            child: Container(
              height: 36,
              padding: EdgeInsets.only(right: 3),
              child: Container(
                width: 9,
                height: 9,
                alignment: Alignment.center,
                child: Image.asset(
                  'images/login_close_ico.png',
                  color: ThemeRepository.getInstance()
                      .getDefaultGrayColor_FF5E687C(),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _toPhoneWidget(String phone) {
    return Offstage(
      offstage: phone == null || phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  /// 部门/项目/城市
  _infoWidget(CommonPersonBean data) {
    List<String> textsList = List();
    String textStr = '';
    if (StringUtils.isNotEmpty(data.department)) {
      textsList.add(data.department);
    }
    if (StringUtils.isNotEmpty(data.classname)) {
      textsList.add(data.classname);
    }
    // if (StringUtils.isNotEmpty(data.projectname)) {
    //   textsList.add(data.projectname);
    // }
    // if (StringUtils.isNotEmpty(data.city)) {
    //   textsList.add(data.city);
    // }
    if (textsList.length > 0) {
      textStr = textsList.join("/");
    } else {
      textStr = null;
    }

    if (textStr == null) {
      return SizedBox(
        height: 0,
      );
    }
    return Padding(
      padding: const EdgeInsets.only(top: 2),
      child: Text(
        textStr,
        style: TextStyle(
            color: textsList.length > 0 ? Color(0xff5e687c) : Color(0xfff95355),
            fontSize: 12),
      ),
    );
  }

  ///管理员
  _adminNumAddBar() {
    return TitleNumberAndAddBtnBarWidget('管理员', widget.oldBean.adminCnt,
        () async {
      //添加管理员
      bool result = await SelectUserPage.navigatorPush(context,
          oldBean: widget.oldBean,
          filterIds: adminList.map((e) => e.fuid).toList());
      if (result != null && result) {
        loading(true);
        //更新管理员列表
        VgEventBus.global.send(AdminChangeEvent('班级部门新增管理员'));
        _viewModel.getDetail(widget.oldBean.getId());

      }
    },type:widget?.type);
  }
}
